#!/usr/bin/env python
#coding: utf-8
#-*- coding: utf-8 -*-

<<<<<<< .mine
"""
trace 域名，根据获得的 IP 检查是通过哪一个第三方出口到电信网络的。
"""

import os,re,sys
=======
import os,re,sys,time
>>>>>>> .r25

def isSameSubNet( ip, ip2 ):
    ip_arr = ip.split('.')
    ip2_arr = ip2.split('.')
    if len(ip_arr) == 4 and len(ip2_arr) == 4 :
        num = ip_arr[0] + ip_arr[1] + ip_arr[2]
        num2 = ip2_arr[0] + ip2_arr[1] + ip2_arr[2]
        if cmp(num, num2) == 0 :
            return True
        else :
            return False
    else :
        return False

def getOutRouter(ip):
    if ip == '218.200.2.170' :
        return '光泽-1出口'
    elif ip == '218.200.2.178' :
        return '沃通出口'
    elif ip == '218.200.2.210' :
        return '光泽-2出口'
    elif ip == '218.200.2.214' :
        return '网联出口'
    elif ip == '218.200.2.218' :
        return '鹏博士出口'
    elif ip == '211.137.131.190' :
        return '铁通出口'
    elif ip == '219.224.102.33' :
        return '教育网出口'
    elif isSameSubNet(ip, '120.192.198.3') :
        return '网内CDN'
    else :
        return None

def getRoundNo():
    return time.strftime('%Y-%m-%d_%H_%S_%M',time.localtime(time.time()))

file_object = open('sitelist.txt')
sitelist = file_object.readlines()
#print sitelist

<<<<<<< .mine
#cmd = 'tracert -w 1000 -h 20'
cmd = 'pathping -p 300 -q 5 '
=======
cmd = 'tracert -w 1000 -h 20 '
>>>>>>> .r25

pstr = r'[\d]+\.[\d]+\.[\d]+\.[\d]+'
#print pstr
p=re.compile( pstr )

outerFile = open('outer_router_' + getRoundNo() + '.txt', 'a')
resultFile = open('trace_log.txt', 'a')

for site in sitelist:
    
    site = site[:-1]
    print site
    result = os.popen(cmd + site).readlines()

    # 可以一次把几件事情都做完。
    router = '北京移动'
    
    for line in result:
        #print line
        # 检查是否第三方出口
        tempList = p.findall(line)
        if tempList :
            for item in tempList:
                #print item
                temp = getOutRouter(item)
                if temp:
                    router = temp
        

        # 填充ip地址的归属信息
    
    # 写第三方出口文件
    print site + '  ' + router
    outerFile.writelines('outer=' + router + '&site=' + site + '\n')
    outerFile.flush()
    

    # 写日志
    
    resultFile.writelines('\n')
    resultFile.writelines('-------- ' + site + ' --------')
    resultFile.writelines(result)
    resultFile.writelines('-------- ' + site + ' END ----')
    resultFile.writelines('\n')
    resultFile.flush()
    
    
outerFile.close()
resultFile.close()



    
    

